package com.baomidou.mybatisplus.criterion;

import java.util.HashMap;
import java.util.Map;

/**
 * 将条件限定对象包装成适合mybatis的规格
 * @author Timothy Ren
 */
public class MybatisCriterion {

	/** 查询条件字符串 */
	private String conditionStr;
	/** 查询排序字符串 */
	private String orderStr;
	/** 查询条件参数值 */
	private Map<String, Object> conditionValues = new HashMap<String, Object>();

	public MybatisCriterion(QueryCriterion qc, QueryOrder qo) {
		// 处理查询条件
		if (qc == null) {
			this.conditionStr = "";
		} else {
			String tempStr = qc.toSqlString();
			Object[] valueArr = qc.getValueArr();
			for (int i = 0; i < valueArr.length; i++) {
				String paramKey = "p" + i;
				tempStr = tempStr.replaceFirst("\\?", "#{criterion.conditionValues." + paramKey + "}");
				this.conditionValues.put(paramKey, valueArr[i]);
			}
			this.conditionStr = tempStr;
		}

		// 处理查询排序
		if (qo == null) {
			this.orderStr = "";
		} else {
			this.orderStr = qo.toSqlString();
		}
	}

	public String getConditionStr() {
		return conditionStr;
	}

	public String getOrderStr() {
		return orderStr;
	}

	public Map<String, Object> getConditionValues() {
		return conditionValues;
	}

	/**
	 * 取得完整的criterion信息，包括where和order by
	 * @return 完整的criterion信息
	 */
	public String getCriterionFullStr() {
		StringBuffer fullbuffer = new StringBuffer();
		if (!isBlank(conditionStr)) {
			fullbuffer.append("where ").append(conditionStr);
		}
		if (!isBlank(orderStr)) {
			fullbuffer.append(" order by ").append(orderStr);
		}
		return fullbuffer.toString();
	}

	private static boolean isBlank(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if ((Character.isWhitespace(str.charAt(i)) == false)) {
				return false;
			}
		}
		return true;
	}

}
